#pragma once

#include <iostream>
#include <memory>
#include <cerrno>
#include <cstring>
#include <cstdlib>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "err.hpp"
#include <functional>
#include <unordered_map>
#include "RingQueue.hpp"
#include <pthread.h>
#include "lockGuard.hpp"
#include "Thread.hpp"

namespace ns_server{
    using namespace std;
    const static uint16_t default_port = 8086;
    using func_t = std::function<std::string(std::string)>;

    class UdpServer{
        public:
            UdpServer(uint16_t port = default_port) : port_(port){
                std::cout << "server addr: " << port_ << std::endl;
                pthread_mutex_init(&lock_, nullptr);

                c_ = new Thread(1, std::bind(&UdpServer::BroadCast, this));
                p_ = new Thread(0, std::bind(&UdpServer::Recv, this));
            }

            void Start(){
                //1.创建socket接口，打开网络文件
                sock_ = socket(AF_INET, SOCK_DGRAM, 0);
                if(sock_ < 0){
                    std::cerr << "creat socket error: " << strerror(errno) << std::endl;
                    exit(SOCKET_ERR);
                }
                std::cout << "creat socket success: " << sock_ << std::endl;

                //2.给服务器指明IP地址和端口port
                struct sockaddr_in local;
                bzero(&local, sizeof(local));

                local.sin_family = AF_INET;
                local.sin_port = htons(port_);
                local.sin_addr.s_addr = INADDR_ANY;
                //local.sin_addr.s_addr = inet_addr(ip_.c_str());//inet_addr函数
                //2.1将字符串IP转化为4字节int
                //2.2将主机序列转化为网络序列

                //3.bind
                if(bind(sock_, (struct sockaddr*)&local, sizeof(local)) < 0){
                    std::cerr << "bind socket error: " << strerror(errno) << std::endl;
                    exit(BIND_ERR);
                }
                std::cout << "bind socket success: " << sock_ << std::endl;

                //线程
                p_->run();
                c_->run();
            }

            void addUser(const std::string& name, const struct sockaddr_in& peer){
                LockGuard guard(&lock_);
                onlineUser_[name] = peer;
            }

            void Recv(){
                char buffer[2048];
                while(true){
                    //收
                    struct sockaddr_in peer;
                    socklen_t len = sizeof(peer);
                    int n = recvfrom(sock_, buffer, sizeof(buffer)-1, 0, (struct sockaddr*)&peer, &len);
                    if(n > 0)
                        buffer[n] = '\0';
                    else
                        continue;

                    //提取client信息
                    std::string clientip = inet_ntoa(peer.sin_addr);
                    uint16_t clientport = ntohs(peer.sin_port);
                    std::cout << clientip << " - " << clientport << "# " << buffer << std::endl;

                    //构建用户
                    string name = clientip;
                    name += "-";
                    name += to_string(clientport);
                    addUser(name, peer);

                    //生产：往队列里push信息
                    rq_.push(buffer);

                    //做业务
                    //std::string message = serverce_(buffer);
                    //发
                    //sendto(sock_, buffer, strlen(buffer), 0, (struct sockaddr*)&peer, sizeof(peer));
                    //sendto(sock_, message.c_str(), message.size(), 0, (struct sockaddr*)&peer, sizeof(peer));
                }
            }

            void BroadCast(){
                while(true){
                    std::string sendString;
                    rq_.pop(&sendString);

                    std::vector<struct sockaddr_in> userPeer;
                    {
                        LockGuard guard(&lock_);
                        for(auto& user:onlineUser_)
                            userPeer.push_back(user.second);
                    }

                    for(auto &user : userPeer){
                        sendto(sock_, sendString.c_str(), sendString.size(), 0, (struct sockaddr*)&user, sizeof(user));
                    }
                }
            }

            ~UdpServer(){
                pthread_mutex_destroy(&lock_);

                c_->join();
                p_->join();

                delete c_;
                delete p_;
            }

        private:
            int sock_;//网络文件描述符
            uint16_t port_;//端口号
            //std::string ip_;//ip号
            //func_t serverce_;
            std::unordered_map<string, sockaddr_in> onlineUser_;
            RingQueue<string> rq_;
            pthread_mutex_t lock_;
            Thread *c_;
            Thread *p_;
    };
}